<template>
  <div>
    <!-- 顶部导航栏 -->
    <header class="exchange-header">
      <a href="#" class="exchange-logo">
        <i class="fas fa-chart-line mr-2"></i>
        区块链证券交易所
      </a>
      
      <div class="user-info">
        <div class="user-avatar">
          <i class="fas fa-user"></i>
        </div>
        <span class="user-name">{{ user?.username }}</span>
        <span class="user-role">{{ user?.role }}</span>
        <span class="wallet-address ml-3">{{ shortenAddress(user?.eoaAddress) }}</span>
        
        <button class="btn btn-sm btn-outline-light ml-3" @click="handleLogout">
          <i class="fas fa-sign-out-alt"></i>
        </button>
      </div>
    </header>

    <!-- 侧边栏 -->
    <aside class="exchange-sidebar">
      <div class="sidebar-sticky">
        <div class="sidebar-heading">主要导航</div>
        <ul class="sidebar-nav">
          <li class="sidebar-nav-item">
            <router-link to="/" class="sidebar-nav-link">
              <i class="fas fa-home"></i>
              <span>首页</span>
            </router-link>
          </li>
          <li class="sidebar-nav-item">
            <router-link to="/user" class="sidebar-nav-link active">
              <i class="fas fa-wallet"></i>
              <span>我的资产</span>
            </router-link>
          </li>
          <li class="sidebar-nav-item">
            <router-link to="/admin" class="sidebar-nav-link">
              <i class="fas fa-chart-bar"></i>
              <span>股票管理</span>
            </router-link>
          </li>
        </ul>
      </div>
    </aside>

    <!-- 主内容区域 -->
    <main class="exchange-content">
      <div v-if="systemMessage" class="alert" :class="systemMessage.type" style="margin-bottom: 20px;">
        {{ systemMessage.text }}
      </div>
      
      <h1 class="h3 mb-4">我的资产</h1>
      
      <div class="row">
        <!-- 我的持股 -->
        <div class="col-12 mb-4">
          <div class="exchange-card">
            <div class="exchange-card-header">
              <h5 class="exchange-card-title">
                <i class="fas fa-wallet mr-2"></i>我的持股
              </h5>
              <button class="btn btn-sm btn-outline-primary" @click="loadMyStocks">
                <i class="fas fa-sync-alt mr-1"></i>刷新
              </button>
            </div>
            <div class="exchange-card-body p-0">
              <div v-if="loading" class="text-center py-5">
                <div class="loading-spinner mx-auto"></div>
                <p class="mt-3 text-muted">正在加载持股数据...</p>
              </div>
              
              <div v-else-if="myStocks.length === 0" class="text-center py-5">
                <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                <p class="text-muted">您还没有持有任何股票</p>
              </div>
              
              <table v-else class="table stock-table mb-0">
                <thead>
                  <tr>
                    <th>股票ID</th>
                    <th>股票名称</th>
                    <th>我的持股</th>
                    <th>总股本</th>
                    <th>持股比例</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="stock in myStocks" :key="stock.stockId">
                    <td><span class="badge badge-primary">{{ stock.stockId }}</span></td>
                    <td><strong>{{ stock.name }}</strong></td>
                    <td><span class="badge badge-success">{{ formatNumber(stock.myShares) }}</span></td>
                    <td>{{ formatNumber(stock.totalShares) }}</td>
                    <td>{{ ((stock.myShares / stock.totalShares) * 100).toFixed(2) }}%</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
        
        <!-- 转让股份 -->
        <div class="col-12">
          <div class="exchange-card">
            <div class="exchange-card-header">
              <h5 class="exchange-card-title">
                <i class="fas fa-exchange-alt mr-2"></i>股票交易
              </h5>
            </div>
            <div class="exchange-card-body">
              <form @submit.prevent="handleTransfer">
                <div class="row">
                  <div class="col-md-6">
                    <div class="form-group">
                      <label>股票ID</label>
                      <select class="form-control" v-model="transferForm.stockId" required>
                        <option value="">选择股票</option>
                        <option v-for="stock in myStocks" :key="stock.stockId" :value="stock.stockId">
                          {{ stock.stockId }} - {{ stock.name }} (持有: {{ formatNumber(stock.myShares) }})
                        </option>
                      </select>
                    </div>
                  </div>
                  
                  <div class="col-md-6">
                    <div class="form-group">
                      <label>接收方地址</label>
                      <input 
                        type="text" 
                        class="form-control" 
                        v-model="transferForm.toAddress"
                        placeholder="0x..."
                        required
                      />
                    </div>
                  </div>
                  
                  <div class="col-md-6">
                    <div class="form-group">
                      <label>转让股数</label>
                      <input 
                        type="number" 
                        class="form-control" 
                        v-model.number="transferForm.shares"
                        placeholder="请输入股数"
                        min="1"
                        required
                      />
                    </div>
                  </div>
                  
                  <div class="col-12">
                    <button type="submit" class="btn btn-primary" :disabled="transferring">
                      <span v-if="transferring">
                        <i class="fas fa-spinner fa-spin mr-2"></i>转让中...
                      </span>
                      <span v-else>
                        <i class="fas fa-paper-plane mr-2"></i>转让股份
                      </span>
                    </button>
                  </div>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useContractStore } from '@/stores/contract'

const router = useRouter()
const authStore = useAuthStore()
const contractStore = useContractStore()

const user = computed(() => authStore.user)
const isAdmin = computed(() => user.value?.role === 'ADMIN')

const myStocks = ref([])
const loading = ref(true)
const transferring = ref(false)
const systemMessage = ref(null)

const transferForm = ref({
  stockId: '',
  toAddress: '',
  shares: ''
})

const shortenAddress = (address) => {
  if (!address) return ''
  return `${address.slice(0, 6)}...${address.slice(-4)}`
}

const formatNumber = (num) => {
  return new Intl.NumberFormat().format(num)
}

const showMessage = (text, type = 'alert-info') => {
  systemMessage.value = { text, type }
  setTimeout(() => {
    systemMessage.value = null
  }, 5000)
}

const loadMyStocks = async () => {
  loading.value = true
  try {
    const nextId = await contractStore.getNextStockId()
    console.log('总股票数:', nextId)
    const stocksList = []
    
    for (let i = 0; i < nextId; i++) {
      try {
        const stock = await contractStore.getStock(i)
        console.log(`股票 ${i}:`, stock)
        if (stock.timestamp > 0) {
          const myShares = await contractStore.getShareholderShares(i, contractStore.currentAccount)
          console.log(`我在股票 ${i} 的持股:`, myShares)
          if (myShares > 0) {
            stocksList.push({
              ...stock,
              myShares
            })
          }
        }
      } catch (error) {
        console.log(`股票 ${i} 查询失败:`, error.message)
      }
    }
    
    console.log('我的持股列表:', stocksList)
    myStocks.value = stocksList
  } catch (error) {
    console.error('加载持股数据失败:', error)
    showMessage('加载持股数据失败: ' + error.message, 'alert-danger')
  } finally {
    loading.value = false
  }
}

const handleTransfer = async () => {
  // 检查表单完整性（stockId 可以为 0，所以需要特殊判断）
  if (transferForm.value.stockId === '' || transferForm.value.stockId === null || 
      !transferForm.value.toAddress || 
      !transferForm.value.shares || transferForm.value.shares <= 0) {
    showMessage('请填写完整信息', 'alert-warning')
    return
  }
  
  transferring.value = true
  try {
    await contractStore.transferShares(
      transferForm.value.stockId,
      contractStore.currentAccount,
      transferForm.value.toAddress,
      transferForm.value.shares
    )
    
    showMessage('股份转让成功！', 'alert-success')
    
    // 重置表单
    transferForm.value = {
      stockId: '',
      toAddress: '',
      shares: ''
    }
    
    // 刷新持股列表
    await loadMyStocks()
  } catch (error) {
    console.error('转让失败:', error)
    showMessage('转让失败: ' + error.message, 'alert-danger')
  } finally {
    transferring.value = false
  }
}

const handleLogout = () => {
  authStore.logout()
  router.push('/login')
}

onMounted(async () => {
  const connected = await contractStore.initProvider()
  if (connected) {
    // 检查账户是否匹配
    const userEoaAddress = user.value?.eoaAddress
    const metamaskAccount = contractStore.currentAccount
    
    if (userEoaAddress && metamaskAccount) {
      if (userEoaAddress.toLowerCase() !== metamaskAccount.toLowerCase()) {
        showMessage(
          `⚠️ 账户不匹配！当前登录：${shortenAddress(userEoaAddress)}，MetaMask：${shortenAddress(metamaskAccount)}。显示的是 MetaMask 账户的持股。`, 
          'alert-warning'
        )
      }
    }
    
    await loadMyStocks()
  } else {
    showMessage('请连接 MetaMask 钱包', 'alert-warning')
    loading.value = false
  }
})
</script>

